// pages/class/class.js
import { getClassListByCourse, addClass } from '../../api/api.js';
Page({
    data: {
        classes: [],
        courseId: '',
        showModal: false,
        newClassName: '',
        newClassCode: ''
    },
    onLoad: function(options) {
        const courseId = options.courseId;
        this.setData({
            courseId: courseId
        });
        this.loadClasses(courseId);
    },

    // 加载班级列表
    loadClasses: function(courseId) {
        getClassListByCourse(courseId).then((res) => {
            console.log(res);
            this.setData({
                classes: res.data.map(item => ({
                    classId: item.classId,
                    className: item.className,
                    classCode: item.classCode
                }))
            });
        }).catch((err) => {
            console.error('获取班级列表失败:', err);
            wx.showToast({
                title: '获取班级列表失败',
                icon: 'none'
            });
        });
    },

    // 显示添加班级弹窗
    showAddClassModal() {
        this.setData({
            showModal: true,
            newClassName: '',
            newClassCode: ''
        });
    },

    // 监听班级名称输入
    onClassNameInput(e) {
        this.setData({
            newClassName: e.detail.value
        });
    },

    // 监听班级代码输入
    onClassCodeInput(e) {
        this.setData({
            newClassCode: e.detail.value
        });
    },

    // 取消添加班级
    cancelAddClass() {
        this.setData({
            showModal: false
        });
    },

    // 确认添加班级
    confirmAddClass() {
        const className = this.data.newClassName.trim();

        if (!className) {
            wx.showToast({
                title: '请输入班级名称',
                icon: 'none'
            });
            return;
        }
        wx.showLoading({
            title: '添加中...',
        });

        // 调用添加班级API
        addClass(className, this.data.courseId).then(res => {
            wx.hideLoading();
            wx.showToast({
                title: '添加成功',
                icon: 'success'
            });
            this.setData({
                showModal: false
            });
            // 重新加载班级列表
            this.loadClasses(this.data.courseId);
        }).catch(err => {
            wx.hideLoading();
            console.error('添加班级失败:', err);
            wx.showToast({
                title: '添加失败，请重试',
                icon: 'none'
            });
        });
    },

    navigateToCheckinHistory: function(e) {
        const classId = e.currentTarget.dataset.classid;

        // 获取当前点击的班级信息
        const currentClass = this.data.classes.find(item => item.classId === classId) || {};

        // 构建URL，传递班级ID、名称和班级码
        const url = `/pages/checkinhistory_student/checkinhistory_student?classId=${classId}&className=${encodeURIComponent(currentClass.className || '')}&classCode=${encodeURIComponent(currentClass.classCode || '')}`;

        wx.navigateTo({
            url: url
        });
    }
});